from sqlalchemy.ext.asyncio import create_async_engine, AsyncEngine, async_sessionmaker
from sqlalchemy.ext.asyncio.session import AsyncSession
import typing as T
from fastapi import Depends
import logging

from .Global import ROOT_DIR, configuration
from .Configuration import ApplicationConfig, DataSourceConfig


def createEngine(configuration: ApplicationConfig):
    datasource: DataSourceConfig = configuration.datasource
    uri = (
        f"{datasource.dataname}+{datasource.driver}://{datasource.username}:{datasource.password}@{datasource.url}"
        if datasource.url is not None
        else f'{datasource.dataname}+{datasource.driver}:///{(ROOT_DIR / "data"/ datasource.database_file).as_posix()}'
    )
    return create_async_engine(
        uri,
        pool_size=20,
        echo=datasource.echo,
        max_overflow=50,
        pool_recycle=3600,
        pool_pre_ping=True,
    )


engine: AsyncEngine = createEngine(configuration)

SessionFactory: async_sessionmaker = async_sessionmaker(engine)


async def getSession():
    async with SessionFactory() as session:
        async with session.begin():
            yield session


Session = T.Annotated[AsyncSession, Depends(getSession)]  # 数据库


logging.info("数据库初始化完成...")
